<?php
/**
 * Created by PhpStorm.
 * User: FDG296
 * Date: 2017/8/30
 * Time: 9:35
 */

namespace backend\controllers;

use backend\models\SysConfig;
use Yii;
use yii\web\AdminController;

class SysSettingController extends AdminController{
    public $layout = false;
    //业务关键字
    public $service = 'SysSetting';

    public function actionIndex(){
        //$group = SysConfig::find()->select('config_group_name')->groupBy('config_group_name')->asArray()->all();

        $group = Yii::$app->db->createCommand('SELECT DISTINCT config_group_id,config_group_name FROM j_sys_config ORDER BY config_group_id')
            ->queryAll();

        $this->saveLog($this->service,'系统设置查询页','VIEW', '' );

        return $this->render('index',['group'=>$group]);
    }

    //获取配置列表
    public function actionGetConfigList(){
        $data = Yii::$app->request->post();
        $condition = array();
        $condition[] = 'and';
        if(!empty($data['search_config_title'])){
            $condition[] = ['like','config_title',$data['search_config_title']];
        }
        if(!empty($data['search_config_group_name'])){
            $condition[] = ['config_group_name'=>$data['search_config_group_name']];
        }
        $query = SysConfig::find()->where($condition);
        $count = $query->count();
        $sort_string = empty($data['columns'][$data['order'][0]['column']]['data']) ? 'id' : $data['columns'][$data['order'][0]['column']]['data'];
        $list = $query->offset($data['start'])->limit($data['length'])
            ->orderBy(array("$sort_string"=>$data['order'][0]['dir'] == 'asc' ? SORT_ASC : SORT_DESC))->asArray()->all();
        if(empty($list)){
            $list = array();
        }

        //相关参数   http://datatables.club/manual/server-side.html
        $result['draw'] = intval($data['draw']);
        $result['recordsTotal'] = intval($count);
        $result['recordsFiltered'] = intval($count);
        $result['data'] = $list;
        return \yii\helpers\Json::encode($result);
    }

    //保存数据
    public function actionSaveConfig(){
        $model = new SysConfig();
        $data = Yii::$app->request->post();
        error_log(print_r($data,1));
        $data_now['config_title'] = $data['config_title'];
        $data_now['config_key'] = $data['config_key'];
        $data_now['config_value'] = $data['config_value'];
        $data_now['memo'] = $data['memo'];
        $data_now['sort'] = empty($data['sort']) ? 1 : $data['sort'];
        $data_now['use_flg'] = $data['use_flg'];

        if(empty($data['config_id'])){//新增
            //新建分组场合
            if(empty($data['config_group_name']) || $data['config_group_name'] == '_new_'){
                $data_now['config_group_name'] = $data['new_config_group_name'];
                $data_now['config_group_id'] = $data['new_config_group_id'];
            }else{
                //使用已有分组的场合
                //根据组ID取组名称----------------------------
                $post = Yii::$app->db->createCommand('SELECT config_group_name FROM j_sys_config WHERE BINARY config_group_id = :config_group_id')
                    ->bindValue(':config_group_id', $data['config_group_name'])
                    ->queryOne();
                $data_now['config_group_name'] = $post['config_group_name'];
                //根据组ID取组名称----------------------------
                $data_now['config_group_id'] = $data['config_group_name'];
            }

            $result_where = ['config_key'=>$data_now['config_key']];
            $result = $model::find()->where($result_where)->asArray()->one();
            if(!empty($result)){
                $this->retJson('KEY已经存在',500);
            }

            $data_now['creator'] = $model->getCreator();
            $data_now['create_time'] = date('Y-m-d H:i:s',time());
            $res = Yii::$app->db->createCommand()->insert('j_sys_config',$data_now)->execute();
        }else{//编辑
            //$data_now['config_group_name'] = $data['new_config_group_name'];
            $data_now['editor'] = $model->getCreator();
            $data_now['edit_time'] = date('Y-m-d H:i:s',time());
            $res = $model::updateAll($data_now, "id=:id",array(':id'=> $data['config_id']));
        }

        if($res > 0){
            $this->saveLog($this->service,'保存设置','VIEW','保存设置 ' . $data_now['config_title'] . "\r\n" .\yii\helpers\Json::encode($data_now));
            $this->retJson('操作成功',200);
        }else{
            $this->retJson('操作失败',500);
        }
    }

    //获取配置详情
    public function actionGetConfigDetail(){
        try{
            $data = Yii::$app->request->post();

            if(empty($data['id'])){
                $this->retJson('参数错误！',9003);
            }
            $result = SysConfig::find()->where(array('id'=>$data['id']))->asArray()->one();
            //$group = SysConfig::find()->select('config_group_name,config_group_id')->groupBy('config_group_name')->asArray()->all();
            $group = Yii::$app->db->createCommand('SELECT DISTINCT config_group_id,config_group_name FROM j_sys_config ORDER BY config_group_id')
                ->queryAll();

            $result['group_arr'] =$group;

            $this->retJson($result,200);

        }catch(\Exception $e){
            //mod by allen.qiang 20180112 异常处理，日志优化 start
            //error_log($e->getMessage());
            error_log('error->' . __METHOD__ . ' error:' . $e->getMessage());
            //mod by allen.qiang 20180112 异常处理，日志优化 end
            $this->retJson('系统异常',9003);
        }
    }

    //启用禁用
    public function actionChangeConfigUseflg(){
        $model = new SysConfig();
        $data = Yii::$app->request->post();

        $mod_data['use_flg'] = $data['use_flg'];
        $mod_data['editor'] = $model->getCreator();
        $mod_data['edit_time'] = date('Y-m-d H:i:s',time());

        $res = $model::updateAll($mod_data, "id = :id",array('id' => $data['id']));

        if($data['use_flg'] == 1){
            $retMsg = '启用';
        }else{
            $retMsg = '禁用';
        }
        if($res > 0){
            $this->saveLog($this->service,$retMsg .'设置','VIEW','设置 ID =  ' . $data['id'] . "\r\n" .\yii\helpers\Json::encode($mod_data));
            $this->retJson('配置' . $retMsg . '成功',200);
        }else{
            $this->retJson('配置' . $retMsg . '失败',500);
        }
    }
}